import React from 'react';
import { useLocation, useNavigate, useParams } from 'react-router-dom';
import { MessagePlugin } from 'tdesign-react';
import { useAuth } from '../../../shared/state/auth.jsx';
import { oauthCallback } from '../../../shared/api/auth';
import { getCurrentUserInfo } from '../../../shared/api/user';

const OAuthRedirect = () => {
  const { signIn, updateUser } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  const { provider } = useParams();

  React.useEffect(() => {
    (async () => {
      try {
        const sp = new URLSearchParams(location.search || '');
        const success = sp.get('success');
        const token = sp.get('token');
        const code = sp.get('code');
        const err = sp.get('error');
        const nameMap = { github: 'GitHub', qq: 'QQ', wechat: '微信' };
        const label = nameMap[String(provider || '').toLowerCase()] || (provider || '第三方');

        if (success === 'false') {
          MessagePlugin.error(`${label}登录失败,请稍后重试`);
        } else if (token) {
          signIn(token, null);
          try { const me = await getCurrentUserInfo(); updateUser(me?.data || me); } catch {}
          if (success === 'true') MessagePlugin.success('登录成功');
        } else if (code) {
          const resp = await oauthCallback(provider || '', code);
          const t = resp?.token || resp?.data?.token || resp?.accessToken || null;
          if (t) {
            signIn(t, null);
            try { const me = await getCurrentUserInfo(); updateUser(me?.data || me); } catch {}
            MessagePlugin.success('登录成功');
          } else {
            MessagePlugin.error('登录失败：缺少令牌');
          }
        }
      } catch (e) {
        MessagePlugin.error(e?.message || e?.data?.message || '登录失败');
      } finally {
        let to = '/';
        try {
          const ret = sessionStorage.getItem('oauth.returnTo');
          if (ret) { to = ret; sessionStorage.removeItem('oauth.returnTo'); }
        } catch {}
        navigate(to, { replace: true });
      }
    })();
  }, [location.search, provider]);

  return null;
};

export default OAuthRedirect;